<script setup>
	import { computed, getCurrentInstance, onMounted, ref } from 'vue'
	const customTabsProps = defineProps({
		list: {
			type: Array,
			default: [],
		},
	})
	const activeIndex = ref(0) // 当前选中的 Tab 索引
	const position = ref([])
	const emit = defineEmits(['changeTab'])

	const onSelectTab = (index, item) => {
		activeIndex.value = index
		emit('changeTab', {index,...item})
	}
	const cursorPosition = computed(() => {
		if (position.value.length === 0) return
		const { width, left } = position.value[activeIndex.value]
		// (自己框-下标)/2+文本在custom-tabs-bar框内left
		return (width - 20) / 2 + left
	})

	onMounted(() => {
		// 创建查询器
		// getCurrentInstance 相当于选项api this
		const querySelector = uni.createSelectorQuery().in(getCurrentInstance())
		// 查找元素, custom-tabs 大的 tabbar-text小的
		// 按照文字的标准来定位
		// left :每一个文本left-大框left = 文本在custom-tabs-bar框内left
		querySelector
			.selectAll('.custom-tabs,.tabbar-text')
			.boundingClientRect(([parent, ...res]) => {
				console.log('parent, res', parent, res)
				position.value = res.map(({ width, left }) => {
					return { width, left: left - parent.left }
				})
			})
			.exec()
	})
</script>
<template>
	<view class="custom-tabs">
		<view
			class="custom-tabs-bar"
			v-for="(item, index) in customTabsProps.list"
			:key="item.label"
			:class="{ active: activeIndex === index }"
			@click="onSelectTab(index, item)"
		>
			<text class="tabbar-text">{{ item.label }}</text>
		</view>
		<view class="custom-tabs-cursor" :style="{ left: cursorPosition + 'px' }">
		</view>
	</view>
</template>

<style lang="scss" scoped>
	.custom-tabs {
		display: flex;
		position: relative;
		padding: 0 30rpx;

		.custom-tabs-bar {
			height: 80rpx;
			line-height: 80rpx;
			color: #979797;
			padding-right: 30rpx;
			position: relative;
			&.active {
				color: #121826;
				font-weight: 500;
			}
		}
		.tabbar-text {
			font-size: 30rpx;
		}
		.custom-tabs-cursor {
			position: absolute;
			bottom: 3px;
			left: 20px;

			width: 20px;
			height: 2px;
			border-radius: 2px;
			background-color: #2cb5a5;
			transition: all 0.3s ease-out;
		}
	}
</style>
